package com.jz.community.modulemine.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.bean.BaseResponseText;
import com.jz.community.basecomm.bean.LoginBaseInfo;
import com.jz.community.basecomm.glideConfig.ImageCatchUtil;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.ActivityUtil;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.DialogUtils;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.basecomm.utils.rxbus.RxBus;
import com.jz.community.basecomm.utils.rxbus.eventType.ToLoginEvent;
import com.jz.community.modulemine.R;
import com.jz.community.modulemine.R2;
import com.jz.community.modulemine.bean.VersionBean;
import com.jz.community.modulemine.information.ui.SetResetPwdActivity;
import com.jz.community.modulemine.net.DeleteJpushTask;
import com.jz.community.modulemine.presenter.SettingPresenter;
import com.jz.community.modulemine.ui.SettingView;
import com.jz.community.modulemine.ui.view.VersionUpdateDialog;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Admin on 2018/4/4 0004.
 */

public class SettingActivity extends BaseMvpActivity<SettingView.View, SettingPresenter> implements SettingView.View {

    @BindView(R2.id.title_back)
    ImageButton titleBack;
    @BindView(R2.id.title_name)
    TextView titleName;
    @BindView(R2.id.text_cache)
    TextView textCache;
    @BindView(R2.id.im_clear_cache)
    LinearLayout imClearCache;
    @BindView(R2.id.version_code)
    TextView versionCode;
    @BindView(R2.id.im_version)
    LinearLayout imVersion;
    @BindView(R2.id.im_afeedback)
    TextView imAfeedback;
    @BindView(R2.id.im_change_password)
    TextView imChangePassword;
    @BindView(R2.id.im_unlogin)
    TextView imUnlogin;
    @BindView(R2.id.title_toolbar)
    Toolbar titleToolbar;

    private LoginBaseInfo loginBaseInfo;

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected int getContentView() {
        return R.layout.module_mine_activity_setting;
    }

    @Override
    protected SettingPresenter createPresenter() {
        return new SettingPresenter(this);
    }

    @Override
    protected void initView() {
        setImmersionBar(titleToolbar);
        titleName.setText("设置");
        versionCode.setText("版本号：v" + getAppVersionName());
        textCache.setText(ImageCatchUtil.getInstance().getCacheSize(this));
        loginBaseInfo = BaseSpUtils.getInstance().getUserBaseInfo(this);
    }

    @Override
    protected void initDatas() {
        super.initDatas();
        if (loginBaseInfo.isInitPwd()) {
            imChangePassword.setText("修改密码");
        } else {
            imChangePassword.setText("设置密码");
        }
    }

    @Override
    protected void addListener() {
        titleBack.setOnClickListener(v -> finish());
        imClearCache.setOnClickListener((View v) -> new DialogUtils(this, R.string.message_clear_cache_confirm).setOnDialogClickListener(new DialogUtils.OnDialogClickListener() {
            @Override
            public void onLeftClick() {

            }

            @Override
            public void onRightClick() {
                onClearCache();
            }
        }));
        imVersion.setOnClickListener(v -> getVersion());

        imAfeedback.setOnClickListener(v -> startActivity(new Intent(SettingActivity.this, FeedbackActivity.class)));

        imUnlogin.setOnClickListener(v -> showUnloginDialog());

        imChangePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (loginBaseInfo.isInitPwd()) {
                    SettingActivity.this.startActivityForResult(new Intent(SettingActivity.this.getContext(), ChangePasswordActivity.class), 141);
                } else {
                    SettingActivity.this.startActivityForResult(new Intent(SettingActivity.this.getContext(), SetResetPwdActivity.class), 142);
                }
            }
        });
    }

    /**
     * 获取应用的当前版本名称
     *
     * @return
     */
    private String getAppVersionName() {
        try {
            return getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    private void showUnloginDialog() {
        new AlertDialog.Builder(this)
                .setItems(R.array.quit, (dialog, which) -> {
                    switch (which) {
                        case 0:
                            quitDeletePushID();
                            mPresenter.memberLoginOut(BaseSpUtils.getInstance().getAccess_token(getContext()));
                            break;
                        case 1:
                            ActivityUtil.exitApp();
                            break;
                    }
                }).show();
    }

    private void getVersion() {
        mPresenter.updateVersion(getAppVersionName());
    }

    private void onClearCache() {
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> e) throws Exception {
                ImageCatchUtil.getInstance().clearImageAllCache(SettingActivity.this);
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Object>() {

                    @Override
                    public void onError(Throwable e) {
                        WpToast.l(SettingActivity.this, "缓存清理失败");
                    }

                    @Override
                    public void onComplete() {
                        WpToast.l(SettingActivity.this, "缓存清理成功");
                        textCache.setText(ImageCatchUtil.getInstance().getCacheSize(SettingActivity.this));
                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(Object o) {

                    }
                });
    }


    @Override
    public void loginOutResult(BaseResponseText responseText) {
        if (responseText.getCode() == 0) {
            cleanSpData();
            ARouter.getInstance().build(RouterIntentConstant.MODULE_AUTHORIZATION_LOGIN).navigation();
            loginOutLogin();
        }
    }

    private void cleanSpData() {
        BaseSpUtils.getInstance().setUserBaseInfo(this, null);
        BaseSpUtils.getInstance().setCurrentCommuity(this, null);
        BaseSpUtils.getInstance().setIsLogin(this, false);
        BaseSpUtils.getInstance().setAccessToken(this, "");
        BaseSpUtils.getInstance().setRefreshToken(this, "");
        BaseSpUtils.getInstance().setNickname(this, "");
        BaseSpUtils.getInstance().setCardPhone(this, "");
    }

    /**
     * 退出登录
     */
    private void loginOutLogin() {
        ToLoginEvent toLoginEvent = new ToLoginEvent();
        toLoginEvent.setToPwdLogin(false);
        RxBus.getInstance().post(toLoginEvent);
        finish();
    }

    //退出删除推送绑定ID
    private void quitDeletePushID() {
        new DeleteJpushTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {

            }
        }).execute();
    }

    private void showVersionDialog(VersionBean entity) {
        VersionUpdateDialog versionDialog = new VersionUpdateDialog(mActivity, entity);
        versionDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 141 && resultCode == 1) {
            finish();
        } else if (requestCode == 142 && resultCode == RESULT_OK) {
            imChangePassword.setText("修改密码");
            loginBaseInfo.setInitPwd(true);
        }
    }

    @Override
    public void setUpdateData(VersionBean versionBean) {
        showVersionDialog(versionBean);
    }

    @Override
    public void showError(String s) {

    }
}
